package com.btpj.jwt.controller;

import com.btpj.jwt.entity.RespBean;
import com.btpj.jwt.entity.User;
import com.btpj.jwt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.Timestamp;

@RestController()
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @PostMapping("/register")
    public RespBean register(String userName, String password, String surePassword) {
        if (userName == null || userName.trim().isEmpty()) {
            return RespBean.error("用户名不能为空");
        }
        if (password == null || password.trim().isEmpty()) {
            return RespBean.error("密码不能为空");
        }
        if (!password.equals(surePassword)) {
            return RespBean.error("密码与确认密码不一致");
        }
        User user = new User();
        user.setName(userName);
        user.setPassword(passwordEncoder.encode(password));
        user.setRegTime(new Timestamp(System.currentTimeMillis()));
        if (userService.register(user)) {
            return RespBean.success("注册成功");
        } else {
            return RespBean.error("注册失败");
        }
    }

    @GetMapping("/userInfo")
    public RespBean getUserInfo() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) userService.loadUserByUsername(authentication.getName());
        return RespBean.success(user);
    }
}
